<template>
  <div class="monthpicker">
    <div class="monthpicker-header">
      <q-btn
        @click="changeYear(false)"
        dense
        :disable="minClean && minClean.getFullYear() === selectedMonth.getFullYear()"
        flat
        icon="navigate_before"
        round
      />
      {{ currentYear.getFullYear() }}
      <q-btn
        @click="changeYear(true)"
        dense
        :disable="maxClean && maxClean.getFullYear() === selectedMonth.getFullYear()"
        flat
        icon="navigate_next"
        round
      />
    </div>
    <q-separator />
    <div class="monthpicker-months">
      <q-btn
        :class="{ 'monthpicker-current': isCurrentMonth(month) }"
        @click="selectMonth(month)"
        :color="isSelectedMonth(month) ? color : ''"
        :disable="isDisabled(month)"
        :flat="!isSelectedMonth(month)"
        :key="month.getTime()"
        :label="month.toLocaleDateString(localeArray, {
          month: 'short',
        })"
        no-caps
        no-outline
        no-ripple
        rounded
        :text-color="isCurrentMonth(month) && !isSelectedMonth(month) ? color : ''"
        v-for="month in displayedMonths"
      />
    </div>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'MonthPicker',
  emits: ['update:modelValue', 'change'],
  props: [
    'color',
    'locale',
    'max',
    'min',
    'modelValue'
  ],
  data () {
    return {
      selectedMonth: null,
      currentYear: new Date()
    }
  },
  methods: {
    changeYear (up) {
      if (up) {
        let d = new Date(this.currentYear);
        d.setMonth(d.getMonth() + 12);

        if (this.maxClean && d > this.maxClean) {
          d = this.maxClean
        }
        this.currentYear = d;
      } else {
        let d = new Date(this.currentYear);
        d.setMonth(d.getMonth() - 12);

        if (this.minClean && d < this.minClean) {
          d = this.minClean
        }
        this.currentYear = d;
      }
    },
    cleanDate (date) {
      if (date && String(date).length === 6) { // 202008这格式
        date = `${String(date).substr(0, 4)}/${String(date).substr(4, 2)}/01`;
      }
      const d = date ? new Date(date) : new Date()
      d.setDate(1)
      d.setHours(0, 0, 0, 0)
      return d
    },
    currentMonth () {
      return this.cleanDate()
    },
    isCurrentMonth (month) {
      return this.currentMonth().getTime() === month.getTime()
    },
    isDisabled (month) {
      let disabled = false

      if ((this.minClean && month < this.minClean) || (this.maxClean && month > this.maxClean)) {
        disabled = true
      }

      return disabled
    },
    isSelectedMonth (month) {
      // console.log('selected:', `${this.selectedMonth.getFullYear()}${this.selectedMonth.getMonth()}`, 'current:', `${month.getFullYear()}${month.getMonth()}`);
      return this.selectedMonth
        ? (this.selectedMonth.getTime() === month.getTime())
        : false
    },
    selectMonth (month) {
      this.selectedMonth = month;
      let m = String(month.getMonth() + 1);
      m = Array(3 - m.length).join('0') + m;

      this.$emit('update:modelValue', `${month.getFullYear()}${m}`);
      this.$emit('change', `${month.getFullYear()}${m}`);
    }
  },
  computed: {
    displayedMonths () {
      const months = [];

      for (let i = 0; i < 12; i++) {
        months.push(new Date(this.currentYear.getFullYear(), i));
      }

      return months;
    },
    localeArray () {
      return this.locale ? [this.locale] : []
    },
    maxClean () {
      return this.max ? this.cleanDate(this.max) : null
    },
    minClean () {
      return this.min ? this.cleanDate(this.min) : null
    }
  },
  watch: {
    value: {
      handler (val) {
        this.selectedMonth = val
          ? this.cleanDate(val)
          : this.currentMonth()
      },
      immediate: true
    }
  }
});
</script>

<style>

.monthpicker {
  width: 250px;
  padding: 10px;
}

.monthpicker-current {
  font-weight: bold;
}

.monthpicker-header {
  align-items: center;
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.monthpicker-months {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 5px;
}

.monthpicker-months .q-btn {
  box-shadow: none;
  margin: 4px 0;
  width: 30%;
}

</style>
